﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Controls;
using PSE.Deployment.SetupBase;
using PSE.Deployment.SetupBase.UI;
using Sinacor.Deployment.Setup.DataAccess;
using Sinacor.Deployment.Setup.Main;

namespace Sinacor.Deployment.Setup.UI
{
    public class BaseDataBaseWizardWindow : BaseWizardWindow
    {
        public BaseDataBaseWizardWindow()
        {

        }

        protected bool TestConnection(string user, string password, string tns, bool isEncrypted)
        {
            bool success = false;
            OracleDataBase db = null;

            try
            {
                db = new OracleDataBase(user, password, tns, isEncrypted);
                db.ExecuteNonQuery("SELECT 1 FROM DUAL");
                success = true;
            }
            catch (Exception ex)
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionTestingException = ex.Message;
                success = false;
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return success;
        }


        protected bool DataBaseSinacorExists(string user, string password, string tns, bool isEncrypted)
        {
            bool dataBaseSinacorExists = false;
            OracleDataBase db = null;

            try
            {
                using (db = new OracleDataBase(user, password, tns, isEncrypted))
                {
                    using (IDataReader dr = db.ExecuteReader("SELECT * FROM ALL_OBJECTS WHERE OBJECT_NAME LIKE '%TFW%'"))
                    {
                        if (dr.Read())
                            dataBaseSinacorExists = true;
                    }
                }

            }
            catch
            {
                dataBaseSinacorExists = false;
            }

            return dataBaseSinacorExists;
        }

        protected void GetTNS(ComboBox combo)
        {
            IList<string> oracleList = PSE.Deployment.Util.Oracle.GetOracleHomes();
            List<string> tnsList = new List<string>();

            if (oracleList.Count == 0)
            {
                combo.ItemsSource = PSE.Deployment.Util.Oracle.LoadTNSNames(string.Empty);
            }
            else
            {
                tnsList.Add("");

                foreach (string oracle in oracleList)
                {
                    tnsList.AddRange(PSE.Deployment.Util.Oracle.LoadTNSNames(oracle));
                }

                combo.ItemsSource = tnsList;
            }
        }
    }
}
